package cn.edu.xmu.software.streamplayer.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.edu.xmu.software.streamplayer.exception.TransferringException;

import android.util.Log;

public class FileUtil {
	public static String TAG = "FileUtil";

	/**
	 * Move the file in oldLocation to newLocation.
	 */
	public static void moveFile(File oldLocation, File newLocation)
			throws TransferringException {

		if (oldLocation.exists()) {
			BufferedInputStream reader = null;
			BufferedOutputStream writer = null;
			try {
				reader = new BufferedInputStream(new FileInputStream(
						oldLocation));
				writer = new BufferedOutputStream(new FileOutputStream(
						newLocation, false));
				byte[] buff = new byte[8192];
				int numChars;
				while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
					writer.write(buff, 0, numChars);
				}
			} catch (IOException ex) {
				throw new TransferringException(
						"IOException when transferring "
								+ oldLocation.getPath() + " to "
								+ newLocation.getPath(), ex);
			} finally {
				try {
					if (reader != null) {
						writer.close();
						reader.close();
					}
				} catch (IOException ex) {
					Log.e(TAG, "Error closing files when transferring "
							+ oldLocation.getPath() + " to "
							+ newLocation.getPath());
				}
			}
		} else {
			throw new TransferringException(
					"Old location does not exist when transferring "
							+ oldLocation.getPath() + " to "
							+ newLocation.getPath());
		}
	}
}
